package thread.lock;

import java.util.concurrent.locks.ReentrantLock;

/** @Package javaSE.thread.lock @Author shimmer @Date 2020/5/14 11:36 @TODO ReentrantLock 显示定义锁 */
public class TestLock {
  public static void main(String[] args) {
    TimeDown timeDown = new TimeDown();
    new Thread(timeDown).start();
    new Thread(timeDown).start();
    new Thread(timeDown).start();
  }
}

class TimeDown implements Runnable {
  int time = 10;
  /** 定义一个锁 */
  private static ReentrantLock lock = new ReentrantLock();

  @Override
  public void run() {
    while (true) {
      lock.lock(); // 上锁
      try {
        if (time > 0) {
          System.out.println(time--);
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        } else {
          break;
        }
      } finally {
        lock.unlock(); // 解锁
      }
    }
  }
}
